package com.ht.api.call.func.impl.ad;

import javax.sql.DataSource;

import com.ht.api.bean.AjaxResult;
import com.ht.api.bean.LoginBean;
import com.ht.api.call.func.IFunctionCall;
import com.ht.api.db.Db;
import com.ht.api.db.Entity;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 获取创意详情
 * @author asq
 * @createTime 2025年3月1日 14:01:20
 */
@Slf4j
public class GetCreativeInfoFunctionCall implements IFunctionCall {

	@Override
	public String getName() {
		return "获取创意详情";
	}

	@Override
	public JSONObject execute(LoginBean me, JSONObject param, AjaxResult result) {
		DataSource ds = me.getDataSource();
		
		// 获取创建ID
        String creativeId = param.getStr("main_id");



        // 查询
        Entity creative = Db.createSqlParser("creative").where("main_id", creativeId).findOne(ds);
        Entity ad = Db.createSqlParser("ad").findById(ds, creative.getStr("ad_id"));
        int adType = ad.getInt("ad_type");

        if (adType == 1 || adType == 2) {
            JSONArray materials = creative.getJSONArray("material");
            if (materials != null) {
                for (int i = 0; i < materials.size(); i++) {
                    JSONObject material = materials.getJSONObject(i);

                    if (material.getStr("type").equals("link")) {
                        String linkId = material.getStr("link_id");

                        Entity link = Db.createSqlParser("short_link").where("main_id", linkId).findOne(ds);
                        String relationId = link.getStr("relation_id");
                        String relationTable = link.getStr("relation_type");

                        Entity relation = Db.createSqlParser(relationTable).where("main_id", relationId).findOne(ds);
                        switch (relationTable) {
                            case "writings":
                                material.set("title", relation.get("title"));
                                material.set("cover", relation.get("cover_image"));
                                material.set("desc", relation.get("desc_text"));
                                break;
                        }

                    }
                }
            }
            creative.set("material", materials);
        }

        
		return JSONUtil.createObj().set("info", creative);
	}
}
